import {StateBusInterface} from "db://assets/Script/State/interface/StateBusInterface";
import {StateMachineInterface} from "db://assets/Script/State/interface/StateMachineInterface";
import {TransitionInterface} from "db://assets/Script/State/interface/TransitionInterface";

export class SubStateMachine<T> implements StateBusInterface<T>, StateMachineInterface<T>, TransitionInterface<T> {
    stateEnum: T;
    //状态Map
    stateMaps: Map<T, StateBusInterface<T>> = new Map()
    //当前状态
    currState: StateBusInterface<T>
    //默认状态
    defaultState: T

    transitionTo(stateEnum: T): void {
        console.log("SubStateMachine开始切换状态")
        if (this.currState && !this.currState.canTransition(stateEnum)) {
            console.log("进入判断 当前状态:", this.currState.stateEnum)
            console.log("进入判断 当前状态是否可以切换为其他状态:", this.currState.canTransition(stateEnum))
            return
        }
        this.currState?.onExit()//如果当前有状态退出当前状态 无状态不执行
        console.log("SubStateMachine从状态map中获取：", stateEnum, "状态")
        this.currState = this.stateMaps.get(stateEnum)
        console.log("SubStateMachine当前状态：", this.currState.stateEnum)
        this.currState?.onEnter()//当前状态是否存在，如果存在执行状态逻辑
    }

    //向stateMaps中添加状态
    add(stateBusInterface: StateBusInterface<T>): void {
        this.stateMaps.set(stateBusInterface.stateEnum, stateBusInterface)
    }

    remove(stateEnum: T): void {
        this.stateMaps.delete(stateEnum)
    }

    onEnter(): void {
        console.log("SubStateMachine执行状态逻辑")
        console.log("SubStateMachine默认状态：", this.defaultState)
        if (this.defaultState) {
            this.transitionTo(this.defaultState)
        }
    }

    onExit(): void {
        console.log("SubStateMachine退出当前状态")
        this.currState?.onExit()
    }

    update(deltaTime: number): void {
        console.log("SubStateMachine更新当前状态")
        this.currState?.update(deltaTime)
    }

    onDestroy(): void {
        throw new Error("Method not implemented.");
    }

    canTransition(to: T): boolean {
        let flag: boolean = this.currState?.canTransition(to);
        console.log("SubStateMachine当前状态是否可以切换下一状态：", flag)
        return flag
    }

}
